package cn.com.anypay.manager.miaoma.miaomaarticle;

import cn.com.anypay.manager.common.controller.BaseController;
import cn.com.anypay.manager.common.enums.ResultCode;
import cn.com.anypay.manager.common.response.ApiResponse;
import cn.com.anypay.manager.miaoma.miaomaarticle.auto.AutoMiaomaArticleUtils;
import cn.com.anypay.manager.miaoma.miaomaarticle.dto.MiaomaArticleDTO;
import jakarta.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/anon/miaomaarticle")
@Validated
public class MiaomaArticleController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(MiaomaArticleController.class);

    @Autowired
    private MiaomaArticleService miaomaArticleService;

    /**
     * 获取已发布文章列表
     */
    @GetMapping("/published")
    public ApiResponse<List<MiaomaArticleDTO>> getPublishedArticles() {
        log.info("获取已发布文章列表");
        QueryWrapper<MiaomaArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "published").orderByDesc("created_time");
        List<MiaomaArticleEntity> list = miaomaArticleService.list(queryWrapper);
        List<MiaomaArticleDTO> dtoList = list.stream()
                .map(AutoMiaomaArticleUtils::convertEntityToDTO)
                .collect(Collectors.toList());
        log.debug("查询到已发布文章数量: {}", dtoList.size());
        return success(dtoList);
    }

    /**
     * 下载文章
     */
    @GetMapping("/{recordId}/download")
    public ApiResponse<String> downloadArticle(@PathVariable Long recordId) {
        log.info("下载文章, id={}", recordId);
        return miaomaArticleService.downloadArticle(recordId);
    }

    /**
     * 更新Miaoma_article信息
     */
    @PutMapping("/manual/{recordId}")
    public ApiResponse<Void> update(@PathVariable Long recordId, @Valid @RequestBody MiaomaArticleDTO dto) {
        log.info("=== 更新文章开始 ===");
        log.info("文章ID: {}", recordId);
        log.info("更新数据: {}", dto);

        // 先查询现有记录
        MiaomaArticleEntity existingRecord = miaomaArticleService.getById(recordId);
        if (existingRecord == null) {
            log.warn("未找到ID为{}的文章记录", recordId);
            return fail(ResultCode.CUSTOM_FAIL, "文章不存在");
        }

        // 使用updateEntity方法正确更新字段，排除系统字段
        AutoMiaomaArticleUtils.updateEntity(dto, existingRecord);

        // 确保ID正确
        existingRecord.setId(recordId);

        // 执行更新
        try {
            miaomaArticleService.updateById(existingRecord);
            log.info("文章更新成功, ID: {}", recordId);
            return success();
        } catch (Exception e) {
            log.error("文章更新失败, ID: {}, 错误: {}", recordId, e.getMessage());
            return fail(ResultCode.CUSTOM_FAIL, "文章更新失败: " + e.getMessage());
        }
    }
}
